package serviceutils

import (
	"errors"
	"os"

	"gitee.com/chenhonghua/golang-toolkit/commandutils"
)

type Service struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	Require     string `json:"require"` // unuse now
	Type        string `json:"type"`    // unuse now
	ExecStart   string `json:"execstart"`
	ExecStop    string `json:"execstop"` // unuse now
	WantedBy    string `json:"watedby"`  // unuse now
}

func (s Service) Reg() error {
	if len(s.Name) == 0 {
		return errors.New("服务名称不能为空")
	}
	if len(s.ExecStart) == 0 {
		return errors.New("服务启动指令不能为空")
	}
	serviceConent := ""
	if len(s.Description) > 0 {
		serviceConent += "[Unit]"
		serviceConent += "\n"
		serviceConent += "Description=" + s.Description
		serviceConent += "\n"
	}
	serviceConent += "[Service]"
	serviceConent += "\n"
	serviceConent += "Type=forking"
	serviceConent += "\n"
	serviceConent += "ExecStart=" + s.ExecStart
	serviceConent += "\n"
	serviceConent += "[Install]"
	serviceConent += "\n"
	serviceConent += "WantedBy=multi-user.target"
	serviceConent += "\n"
	e := os.WriteFile("/lib/systemd/system/"+s.Name+".service", []byte(serviceConent), os.ModePerm)
	if e != nil {
		return errors.New("无法注册" + s.Name + "服务到系统")
	}
	_, e = commandutils.Command("systemctl daemon-reload")
	return e
}

func (s Service) Enable() error {
	if len(s.Name) == 0 {
		return errors.New("服务名称不能为空")
	}
	_, e := commandutils.Command("systemctl enable " + s.Name)
	return e
}

func (s Service) Start() error {
	if len(s.Name) == 0 {
		return errors.New("服务名称不能为空")
	}
	_, e := commandutils.Command("systemctl start " + s.Name)
	return e
}

func (s Service) Status() string {
	r, _ := commandutils.Command("systemctl status " + s.Name)
	return r
}

func (s Service) Log() string {
	l, _ := commandutils.Command("journalctl -u " + s.Name)
	return l
}

func List() string {
	r, _ := commandutils.Command("systemctl")
	return r
}
